package xyz.gpgl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import xyz.gpgl.config.properties.WebProperties;
import xyz.gpgl.config.security.MyAuthenctiationFailureHandler;
import xyz.gpgl.config.security.MyAuthenticationSuccessHandler;
import xyz.gpgl.erp.sys.service.impl.MyUserDetailServiceImpl;

@Configuration
@EnableWebSecurity  //启用Web安全功能
@EnableConfigurationProperties({WebProperties.class})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private WebProperties webProperties;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
        //访问"/"和"/static/**"路径的请求都允许
		http
			.authorizeRequests().antMatchers("/static/**").permitAll()
			.anyRequest()//而其他的请求都需要认证
			.authenticated()
				.and()
			.formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/index")
				.failureHandler(myAuthenctiationFailureHandler())
				.successHandler(myAuthenticationSuccessHandler())
				.and()
			.logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()
				.and()
            .csrf().disable()
            .headers()
	            .frameOptions().sameOrigin()
	            .httpStrictTransportSecurity().disable()
			;
	}

	/**
	 * 登录失败处理器
	 * @return
	 */
	@Bean
	public AuthenticationFailureHandler myAuthenctiationFailureHandler(){
		return new MyAuthenctiationFailureHandler();
	}

	/**
	 * 登录成功处理器
	 * @return
	 */
	@Bean
	public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
		return new MyAuthenticationSuccessHandler(webProperties.getIndexUrl());
	}

	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailServiceImpl()).passwordEncoder(passwordEncoder());
    }

    /**
     * 密码加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public MyUserDetailServiceImpl myUserDetailServiceImpl() {
    	return new MyUserDetailServiceImpl();
    }

}
